﻿using AnlianCommon.Common.Domains.SheepManagement;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using AutoMapper;
using MediatR;

namespace SheepCommon.API.SheepCommands.SheepDiees
{
    public class SheepDieCreateHandler : IRequestHandler<SheepDieCreateCommand, Result>
    {
        private readonly IBaseRepository<SheepDie> _sheepDieRepository;
        private readonly IMapper _mapper;

        public SheepDieCreateHandler(IBaseRepository<SheepDie> sheepDieRepository, IMapper mapper)
        {
            _sheepDieRepository = sheepDieRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(SheepDieCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code=(int)CommonErrorCode.Added};
            try
            {
                SheepDie sheepDie = _mapper.Map<SheepDie>(request);
                sheepDie.DieDate = DateTime.Now;//羊只死亡日期
                sheepDie.CreatedOwnerId = "张三";
                sheepDie.CreatedTime = DateTime.Now;
                var res = await _sheepDieRepository.Add(sheepDie);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加成功";
                }
                else
                {
                    result.Code = (int)CommonErrorCode.Added;
                    result.Msg = "添加失败";
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
